from sqlalchemy import and_
from datetime import datetime
from flask import current_app
from app import db
from app.models.user import User
from app.models.user_photo import UserPhoto
from app.models.file_upload import FileUpload


class UserPhotoService:
    """用户照片服务层"""
    
    @staticmethod
    def get_user_photos(user_id):
        """获取用户照片列表"""
        photos = UserPhoto.query.filter_by(user_id=user_id).order_by(UserPhoto.sort_order.asc()).all()
        return [photo.to_dict() for photo in photos]
    
    @staticmethod
    def add_user_photo(user_id, file_id, is_avatar=False):
        """关联照片到用户"""
        # 检查文件是否存在
        file_upload = FileUpload.query.get(file_id)
        if not file_upload:
            raise Exception("文件不存在")
        
        # 检查用户是否存在
        user = User.query.get(user_id)
        if not user:
            raise Exception("用户不存在")
        
        # 检查照片数量限制（最多9张）
        photo_count = UserPhoto.query.filter_by(user_id=user_id).count()
        if photo_count >= 9:
            raise Exception("照片数量已达到上限（9张）")
        
        # 如果设置为头像，取消其他照片的头像标记
        if is_avatar:
            UserPhoto.query.filter_by(user_id=user_id, is_avatar=True).update({'is_avatar': False})
        
        # 创建照片记录
        max_sort = db.session.query(db.func.max(UserPhoto.sort_order)).filter_by(user_id=user_id).scalar() or 0
        
        user_photo = UserPhoto(
            user_id=user_id,
            photo_url=file_upload.file_path,
            is_avatar=is_avatar,
            sort_order=max_sort + 1,
            status=1  # 待审核
        )
        
        db.session.add(user_photo)
        
        # 如果是头像，同时更新用户表的头像字段
        if is_avatar:
            user.avatar = file_upload.file_path
        
        db.session.commit()
        return user_photo.to_dict()
    
    @staticmethod
    def update_photo_info(user_id, photo_id, is_avatar=None, sort_order=None):
        """更新照片信息"""
        photo = UserPhoto.query.filter_by(id=photo_id, user_id=user_id).first()
        if not photo:
            raise Exception("照片不存在")
        
        # 更新头像标记
        if is_avatar is not None:
            if is_avatar:
                # 取消其他照片的头像标记
                UserPhoto.query.filter_by(user_id=user_id, is_avatar=True).update({'is_avatar': False})
                photo.is_avatar = True
                
                # 更新用户表的头像字段
                user = User.query.get(user_id)
                if user:
                    user.avatar = photo.photo_url
            else:
                photo.is_avatar = False
        
        # 更新排序
        if sort_order is not None:
            photo.sort_order = sort_order
        
        db.session.commit()
        return photo.to_dict()
    
    @staticmethod
    def delete_user_photo(user_id, photo_id):
        """删除用户照片关联"""
        photo = UserPhoto.query.filter_by(id=photo_id, user_id=user_id).first()
        if not photo:
            return False
        
        was_avatar = photo.is_avatar
        db.session.delete(photo)
        
        # 如果删除的是头像，清空用户表的头像字段
        if was_avatar:
            user = User.query.get(user_id)
            if user:
                user.avatar = None
        
        db.session.commit()
        return True
    
    @staticmethod
    def sort_user_photos(user_id, photo_orders):
        """照片排序"""
        for order_data in photo_orders:
            photo_id = order_data.get('id')
            sort_order = order_data.get('sort_order')
            
            photo = UserPhoto.query.filter_by(id=photo_id, user_id=user_id).first()
            if photo:
                photo.sort_order = sort_order
        
        db.session.commit()
        return UserPhotoService.get_user_photos(user_id)
    
    @staticmethod
    def set_avatar(user_id, photo_id):
        """设置头像"""
        # 取消所有照片的头像标记
        UserPhoto.query.filter_by(user_id=user_id, is_avatar=True).update({'is_avatar': False})
        
        # 设置指定照片为头像
        photo = UserPhoto.query.filter_by(id=photo_id, user_id=user_id).first()
        if not photo:
            raise Exception("照片不存在")
        
        photo.is_avatar = True
        
        # 更新用户表的头像字段
        user = User.query.get(user_id)
        if user:
            user.avatar = photo.photo_url
        
        db.session.commit()
        return photo.to_dict() 